<template>
    <BasePage>
        <el-form slot="form" :inline="true" size="medium" @submit.native.prevent>
            <el-form-item label="创建日期">
                <el-date-picker
                    v-model="form.date"
                    type="daterange"
                    value-format="yyyy-MM-dd"
                    :editable="false"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                />
            </el-form-item>
            <el-form-item label="巡查部门">
                <OrgSelect :value.sync="form.deptIds" clearable />
            </el-form-item>
            <el-form-item label="巡查类型">
                <el-select v-model="form.type" clearable placeholder="请选择" style="width: 100%">
                    <el-option v-for="item in patrolTypeOptions" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <BaseButton v-permission="{ btnCode: 'dlyh_c9_d21_2' }" @click="handleFilter">查询</BaseButton>
                <BaseButton type="second" @click="resetConditions">重置</BaseButton>
            </el-form-item>
        </el-form>

        <div slot="button">
            <BaseButton v-permission="{ btnCode: 'dlyh_c9_d23_2' }" @click="showDialog('add')">新建巡查记录</BaseButton>
            <BaseButton v-permission="{ btnCode: 'dlyh_c9_d25_2' }" @click="showDialog('download')">批量下载</BaseButton>
            <FormDialog
                ref="dialogFormRef"
                :title="dialogTitle"
                :items="dialogFormItem"
                :rules="dialogRules"
                :form.sync="dialogForm"
                :visible.sync="dialogVisible"
                @submit="handleSubmit"
            />
        </div>

        <!--数据列表区-->
        <BaseTable slot="table" v-loading="listLoading" :columns="columns" :data="list" row-key="id" height="calc(100% - 73px)" highlight-current-row>
            <template #number="{ scope: { row} }">
                <span class="cursor-pointer text-blue-light" @click="handleDetail(row)">{{ row.number }}</span>
            </template>
            <template #handle="{ scope: { row } }">
                <BaseButton v-permission="{ btnCode: 'dlyh_c9_d22_2' }" type="text" @click="handleDownload(row)">下载</BaseButton>
            </template>
        </BaseTable>
        <!--分页组件-->
        <Pagination
            slot="pagination"
            :current-page.sync="page.pageNo"
            :page-size.sync="page.pageSize"
            :total="page.total"
            @current-change="getList"
            @size-change="getList"
        />
    </BasePage>
</template>

<script>
import BasePage from '@/layouts/BasePage'
import { InspectionRecordModel } from '@/models'
import { InspectionRecordApi } from '@/api'
import downLoad from '@/utils/blob-download'
import { patrolType } from '../../constants'
import KeepAliveHandler from '@/mixins/keepAliveHandler'
import { cloneDeep } from 'lodash-es'

export default {
    name: 'RecordList',
    components: {
        BasePage
    },
    mixins: [
        KeepAliveHandler({
            defaultCondition: {
                date: [],
                type: null,
                deptIds: []
            },
            conditionObjKey: 'form'
        })
    ],
    data() {
        return {
            patrolTypeOptions: patrolType,
            model: new InspectionRecordModel(),
            recordApi: new InspectionRecordApi(),
            form: { date: [], deptIds: [] },
            listLoading: true,
            list: [],
            page: {
                pageNo: 1,
                pageSize: 10,
                total: 0
            },
            columns: Object.freeze([
                {
                    slot: 'number',
                    attrs: {
                        prop: 'number',
                        label: '编号',
                        width: '160',
                        'show-overflow-tooltip': true
                    }
                },
                {
                    attrs: {
                        prop: 'typeName',
                        label: '巡查类型',
                        'show-overflow-tooltip': true,
                        'min-width': '160'
                    }
                },
                {
                    attrs: {
                        prop: 'createTime',
                        label: '创建日期',
                        'show-overflow-tooltip': true,
                        width: '140'
                    }
                },
                {
                    attrs: {
                        prop: 'deptName',
                        label: '巡查部门',
                        'show-overflow-tooltip': true,
                        'min-width': '160'
                    }
                },
                {
                    attrs: {
                        prop: 'inspectUsersName',
                        label: '巡查人员',
                        'show-overflow-tooltip': true,
                        'min-width': '160'
                    }
                },
                {
                    attrs: {
                        prop: 'principalName',
                        label: '负责人',
                        'show-overflow-tooltip': true,
                        'min-width': '160'
                    }
                },
                {
                    slot: 'handle',
                    attrs: {
                        label: '操作',
                        width: '140',
                        fixed: 'right'
                    }
                }
            ]),
            colorMap: {
                1: '',
                2: 'color-red',
                3: 'color-yellow',
                4: 'color-green'
            },
            dialogFormItem: [],
            dialogRules: {
                type: [{ required: true, message: '请选择巡查类型', trigger: 'change' }],
                month: [{ required: true, message: '请选择月份', trigger: 'change' }]
            },
            dialogForm: {},
            dialogVisible: false,
            dialogTitle: '',
            dialogType: ''
        }
    },
    created() {
        this.getList()
    },
    methods: {
        getList() {
            this.listLoading = true
            const data = cloneDeep(this.form)
            data.startDate = data.date ? data.date[0] : null
            data.endDate = data.date ? data.date[1] : null
            data.deptIds = data.deptIds.toString()
            return this.model
                .getList(data, this.page)
                .then((res) => {
                    this.list = res.list || []
                    this.page.total = res.totalCount
                })
                .finally(() => {
                    this.listLoading = false
                })
        },
        // 查询
        async handleFilter() {
            this.page.pageNo = 1
            await this.getList()
        },
        handleAdd() {
            const typeMap = {
                1: 'AddDailyNightRecord',
                2: 'AddDailyNightRecord',
                3: 'AddCulvertRecord',
                4: 'AddBridgeRecord',
                5: 'AddRoadbedRecord',
                6: 'AddTunnelRecord',
                7: 'AddTunnelRecord',
                8: 'AddRoadworkRecord'
            }
            this.$router.push({
                name: typeMap[this.dialogForm.type],
                query: {
                    type: this.dialogForm.type,
                    pageType: 'record'
                }
            })
        },
        handleDetail(row) {
            this.$router.push({
                name: 'RecordDetail',
                query: {
                    id: row.id,
                    number: row.number,
                }
            })
        },
        handleDownload(row) {
            const data = { id: row.id }
            const name = row.createTime + row.typeName
            this.download(data, name)
        },
        download(data, name) {
            const url = this.recordApi.downLoadExcel()
            downLoad(url, data, name, 'Zip')
        },
        checkDownLoadExcel(data) {
            return this.model.checkDownLoadExcel(data).then((res) => {
                console.log(res)
            })
        },
        // 新增/下载记录
        async handleSubmit(valida) {
            if (!valida) {
                return
            }
            this.dialogVisible = false
            if (this.dialogType === 'add') {
                this.handleAdd()
            } else if (this.dialogType === 'download') {
                const data = {
                    startDate: this.dialogForm.month + '-01',
                    endDate: this.dialogForm.month + '-01',
                    type: this.dialogForm.type
                }
                this.model
                    .checkDownLoadExcel(data)
                    .then(() => {
                        // 展示提示框
                        const html = '正在下载文件，由于下载内容较多，请稍后…<br>稍后可在浏览器下载记录查看<br><span class="color-blue">5s后自动消失</span>'
                        this.$msgbox({
                            title: '提示',
                            message: html,
                            dangerouslyUseHTMLString: true,
                            type: 'warning',
                            showConfirmButton: false
                        })
                        setTimeout(() => {
                            this.$msgbox.close()
                        }, 5000)
                        // 请求正常时才进行下载
                        const typeName = (this.patrolTypeOptions.find((item) => item.id === this.dialogForm.type) || {}).name
                        const name = `${this.dialogForm.month}${typeName}单`
                        // 下载具体文件
                        this.download(data, name)
                    })
                    .catch((error) => {
                        console.log(error)
                        return
                    })
            }
        },
        showDialog(type) {
            this.dialogType = type
            this.dialogForm = {}
            // 表格里需要value和label
            const patrolTypeOptions = this.patrolTypeOptions.map((item) => {
                return {
                    value: item.id,
                    label: item.name
                }
            })
            if (type === 'add') {
                this.dialogTitle = '请选择巡查类型'
                this.dialogFormItem = [
                    {
                        type: 'select',
                        model: 'type',
                        label: '巡查类型',
                        options: patrolTypeOptions
                    }
                ]
            } else if (type === 'download') {
                this.dialogTitle = '请筛选本次下载的文件'
                this.dialogFormItem = [
                    {
                        type: 'select',
                        model: 'type',
                        label: '巡查类型',
                        options: patrolTypeOptions
                    },
                    {
                        type: 'picker',
                        model: 'month',
                        label: '月份',
                        pikerType: 'month',
                        format: 'yyyy-MM'
                    }
                ]
            }
            this.$refs['dialogFormRef'].show()
        }
    }
}
</script>

<style lang="scss" scoped>
</style>
